/*
    Deferred Shader
*/

uniform sampler2D shading_ssao;
uniform sampler2D overbright;
uniform sampler2D shading_ssao_blur;
uniform sampler2D overbright_blur;
uniform sampler2D normalDepthTex;

varying vec2 coord;
varying vec2 uv;

// #define DOF_DIST_MIN 1.4
// #define DOF_DIST_MAX 1.5
//#define DOF_FAR_FACTOR 1.0
//#define DOF_DIST_MAX_FACTOR DOF_DIST_MAX * -DOF_FAR_FACTOR
#define BLOOM_FACTOR 0.5

// switches
uniform int sw_AO_ONLY;
uniform int sw_DOF;
uniform int sw_BLOOM;

// handy
const vec3 CL = vec3(1.0, 0.0, 0.5);

void main() {
    float DOF_FOCUS = texture2D(normalDepthTex, CL.zz).a;    // auto-focus on center point
    float DOF_LENGTH = max(0.1, DOF_FOCUS * 0.5 - 0.5);        // auto dof length
    vec4 result_ssao = texture2D(shading_ssao, uv);
    vec3 result = result_ssao.rgb;
    float ssao = result_ssao.a;
    vec4 result_ssao_blur = texture2D(shading_ssao_blur, uv);
    vec3 result_blur = result_ssao_blur.rgb;
    float ssao_blur = result_ssao_blur.a;
    float depth = texture2D(normalDepthTex, uv).a;
    
    
    // simulate depth of field by blending with blurred layer
    float blend, diff;
//++if (sw_DOF == 1) {
        diff = max(0.0, abs(depth - DOF_FOCUS) - DOF_LENGTH);
        blend = min(1.0, diff);
//++} else {
//++    blend = 0.0;
//++}
    
    // add blend from edge detect (the edge weight is found in alpha channel of overbright)
    blend = min(1.0, texture2D(overbright, uv).a * 0.6 + blend);
    result = mix(result, result_blur, blend);
    
    blend = blend * 0.15 + 0.85;    // favour the blur version
    ssao = mix(ssao, ssao_blur, blend);
    
    vec3 bloom = CL.yyy;
//++if (sw_BLOOM == 1)
        bloom = texture2D(overbright_blur, uv).rgb * BLOOM_FACTOR;
    
//++if (sw_AO_ONLY == 1) {
//++gl_FragData[0].rgb = vec3(ssao);
//++} else {
        //if (ssao == 1.0)
        //    gl_FragData[0].rgb = result + bloom;
        //else if (ssao == 0.0)
        //    gl_FragData[0].rgb = CL.yyy;
        //else
            gl_FragData[0].rgb = result * ssao + bloom;            
//++}   
    
    // gl_FragData[0].rgb = result_blur;
    // gl_FragData[0].rgb = texture2D(normalDepthTex, uv).rgb;
    // gl_FragData[0].rgb = texture2D(normalDepthTex, uv).aaa / 8.0;
}


